﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using LandPortMoblieWeb.Models;
using LandPortMoblieWeb.Service;
using LandPortMoblieWeb.Filter;
using LandPortMoblieWeb.Helper;

namespace LandPortMoblieWeb.Controllers
{

    [Authorize]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Index

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login()
        {          
            var cc = new HelpCookies().GetCookiseInfo("uid");
            ViewBag.telmessage = cc; 
            return View();
        }

        //
        // POST: /Account/Login

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(User model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var cc = new UserService().IsLoginPass(model);

                    if (cc)
                    {
                        FormsAuthentication.SetAuthCookie(model.LoginName, true);
                        new HelpCookies().SetCookise("uid", model.LoginName);
                        Helper.HelpCookies.CurrentUserObject = new UserService().GetUserModel(model.LoginName);

                        if (model.Password == "123456")
                        {
                            return RedirectToAction("ChangePassword", "Account", new { type = "system" });
                        }
                        else
                        {

                            return Json("success");
                            //  return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        return Json("提供的用户名或密码不正确");
                    }
                }
            }
            catch (Exception ex)
            { 
               new Service.LogService().Log(ex.Message);
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            return View();
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        public ActionResult ChangePassword()
        {
            var cc = Request["type"];
            Helper.Common.isFristLogin = cc;
            ViewBag.cc = cc;
            ViewBag.RealName = Helper.HelpCookies.CurrentUserObject.Name;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            ViewBag.RealName = Helper.HelpCookies.CurrentUserObject.Name;
            ViewBag.cc = Helper.Common.isFristLogin;

            if (model.NewPassword == "123456")
            {
                ModelState.AddModelError("", "当前密码不允许设置为初始密码。");
                return View(model);
            }
            if (ModelState.IsValid)
            {

                // 在某些出错情况下，ChangePassword 将引发异常，
                // 而不是返回 false。
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded =new Service.UserService().ChangePassword(Helper.HelpCookies.CurrentUserObject.Id, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }


        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region 状态代码
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入其他电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
